//
//  StatusBar.swift
//  RunCat
//
//  Created by wdhcr on 2023/2/20.
//

import SwiftUI

struct StatusBar: View {

    let timerIntervals = [0.025,0.035,0.045,0.055,0.75,0.09,0.16,0.20, 0.22,0.24]
    
    @State var intervalIndex = 8
    
    @State var width: CGFloat
    @State var height: CGFloat
    
    @State var imageIndex = 0
    
    @State var imageName = imagesObj[0].urls[0]
    
    @AppStorage("CurrentIconIndex") private var currentIconIndex =  0
    
    @StateObject var cpuInfo = CpuUsage()
    
    init(width:CGFloat, height: CGFloat) {
        self.width = width
        self.height = height
    }
    
    var body: some View {
        
        
        let timer = Timer.publish(every:timerIntervals[intervalIndex],
                                  on: .main, in: .common).autoconnect()
        HStack {
            Image(imageName).resizable()
        }.onReceive(timer) {_ in
            imageIndex = (imageIndex + 1) % imagesObj[currentIconIndex].urls.count
            imageName = "\(imagesObj[currentIconIndex].urls[imageIndex])"
            intervalIndex = cpuUsage()
        }
    }
    
    func cpuUsage() -> Int {
        return  Int((1-cpuInfo.cuse) * 10)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        StatusBar(width: 100, height: 100)
    }
}
